<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElCard, ElRow, ElCol, ElStatistic } from 'element-plus'
import * as echarts from 'echarts'

// 模拟数据
const statisticsData = ref({
  totalInventory: 1258,
  weeklyOutbound: 356,
  weeklyInbound: 412,
  totalProducts: 78,
  totalStores: 12,
  lowStockItems: 8,
})

// 模拟七日出入库数据
const weeklyData = ref({
  dates: ['6-10', '6-11', '6-12', '6-13', '6-14', '6-15', '6-16'],
  inbound: [45, 52, 68, 70, 55, 62, 60],
  outbound: [42, 38, 55, 62, 48, 50, 61],
})

// 模拟商品分类占比数据
const categoryData = ref([
  { value: 35, name: '食品饮料' },
  { value: 20, name: '日用百货' },
  { value: 15, name: '服装鞋帽' },
  { value: 10, name: '电子产品' },
  { value: 20, name: '其他' },
])

// 模拟热销商品数据
const hotSellingData = ref([
  { name: '有机大米', sales: 120 },
  { name: '进口牛奶', sales: 110 },
  { name: '纯棉T恤', sales: 95 },
  { name: '儿童玩具', sales: 85 },
  { name: '厨房用具', sales: 70 },
])

let weeklyChartInstance = null
let categoryChartInstance = null
let hotSellingChartInstance = null
let resizeHandler = null

const resizeCharts = () => {
  weeklyChartInstance?.resize()
  categoryChartInstance?.resize()
  hotSellingChartInstance?.resize()
}

const disposeCharts = () => {
  if (weeklyChartInstance) {
    weeklyChartInstance.dispose()
    weeklyChartInstance = null
  }
  if (categoryChartInstance) {
    categoryChartInstance.dispose()
    categoryChartInstance = null
  }
  if (hotSellingChartInstance) {
    hotSellingChartInstance.dispose()
    hotSellingChartInstance = null
  }
}

// 初始化图表
onMounted(() => {
  const weeklyChartEl = document.getElementById('weekly-chart')
  const categoryChartEl = document.getElementById('category-chart')
  const hotSellingChartEl = document.getElementById('hot-selling-chart')

  if (!weeklyChartEl || !categoryChartEl || !hotSellingChartEl) {
    return
  }

  // 初始化七日出入库趋势图
  weeklyChartInstance = echarts.init(weeklyChartEl)
  weeklyChartInstance.setOption({
    backgroundColor: 'transparent',
    title: {
      text: '七日出入库趋势',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        fontFamily: 'Roboto',
      },
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.8)',
      borderRadius: 10,
      borderWidth: 0,
      textStyle: {
        color: '#333',
      },
      extraCssText: 'backdrop-filter: blur(10px);',
    },
    legend: {
      data: ['入库数量', '出库数量'],
      bottom: '0',
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontFamily: 'Roboto',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: weeklyData.value.dates,
      axisLine: {
        lineStyle: {
          color: '#ddd',
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          color: '#eee',
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '入库数量',
        type: 'line',
        data: weeklyData.value.inbound,
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 185, 107, 0.5)' },
            { offset: 1, color: 'rgba(0, 185, 107, 0.05)' },
          ]),
        },
        itemStyle: {
          color: '#00b96b',
          borderWidth: 2,
          borderColor: '#fff',
        },
      },
      {
        name: '出库数量',
        type: 'line',
        data: weeklyData.value.outbound,
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 137, 34, 0.5)' },
            { offset: 1, color: 'rgba(0, 137, 34, 0.05)' },
          ]),
        },
        itemStyle: {
          color: 'rgb(0, 137, 34)',
          borderWidth: 2,
          borderColor: '#fff',
        },
      },
    ],
  })

  // 初始化商品分类占比图
  categoryChartInstance = echarts.init(categoryChartEl)
  categoryChartInstance.setOption({
    backgroundColor: 'transparent',
    title: {
      text: '商品分类占比',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        fontFamily: 'Roboto',
      },
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.8)',
      borderRadius: 10,
      borderWidth: 0,
      textStyle: {
        color: '#333',
      },
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      extraCssText: 'backdrop-filter: blur(10px);',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontFamily: 'Roboto',
      },
    },
    series: [
      {
        name: '商品分类',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold',
            fontFamily: 'Roboto',
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.2)',
          },
        },
        labelLine: {
          show: false,
        },
        data: categoryData.value,
        color: ['#00b96b', 'rgb(0, 137, 34)', '#ffb700', '#ff7b00', '#909399'],
      },
    ],
  })

  // 初始化热销商品图
  hotSellingChartInstance = echarts.init(hotSellingChartEl)
  hotSellingChartInstance.setOption({
    backgroundColor: 'transparent',
    title: {
      text: '热销商品TOP5',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        fontFamily: 'Roboto',
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      backgroundColor: 'rgba(255, 255, 255, 0.8)',
      borderRadius: 10,
      borderWidth: 0,
      textStyle: {
        color: '#333',
      },
      extraCssText: 'backdrop-filter: blur(10px);',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '20%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          color: '#eee',
          type: 'dashed',
        },
      },
    },
    yAxis: {
      type: 'category',
      data: hotSellingData.value.map((item) => item.name),
      axisLine: {
        lineStyle: {
          color: '#ddd',
        },
      },
      axisTick: {
        show: false,
      },
    },
    series: [
      {
        name: '销售量',
        type: 'bar',
        data: hotSellingData.value.map((item) => item.sales),
        barWidth: '60%',
        itemStyle: {
          borderRadius: [0, 20, 20, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: 'rgba(0, 185, 107, 0.8)' },
            { offset: 1, color: 'rgba(0, 137, 34, 0.8)' },
          ]),
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}',
          fontFamily: 'Roboto',
          color: '#333',
        },
      },
    ],
  })

  // 监听窗口大小变化，调整图表大小
  resizeHandler = () => {
    resizeCharts()
  }
  window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler)
    resizeHandler = null
  }
  disposeCharts()
})
</script>

<template>
  <div class="dashboard-container">
    <h2 class="dashboard-title">商城系统仪表盘</h2>

    <!-- 统计数据卡片 -->
    <el-row :gutter="20" class="data-cards">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon inventory-icon">
            <el-icon><LineMdGaugeTwotone /></el-icon>
          </div>
          <el-statistic :value="statisticsData.totalInventory" title="商品总库存数量">
            <template #suffix>
              <span class="unit">件</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon outbound-icon">
            <el-icon><LineMdCompassFilledLoop /></el-icon>
          </div>
          <el-statistic :value="statisticsData.weeklyOutbound" title="七日出库数量">
            <template #suffix>
              <span class="unit">件</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon inbound-icon">
            <el-icon><LineMdPlus /></el-icon>
          </div>
          <el-statistic :value="statisticsData.weeklyInbound" title="七日入库数量">
            <template #suffix>
              <span class="unit">件</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="data-cards">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon products-icon">
            <i class="el-icon-shopping-cart">
              <LineMdLightbulbFilled />
            </i>
          </div>
          <el-statistic :value="statisticsData.totalProducts" title="商品种类数量">
            <template #suffix>
              <span class="unit">种</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon stores-icon">
            <el-icon><LineMdHomeTwotone /></el-icon>
          </div>
          <el-statistic :value="statisticsData.totalStores" title="门店数量">
            <template #suffix>
              <span class="unit">家</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover" class="data-card warning-card">
          <div class="card-icon warning-icon">
            <el-icon><LineMdCogFilledLoop /></el-icon>
          </div>
          <el-statistic :value="statisticsData.lowStockItems" title="库存预警商品">
            <template #suffix>
              <span class="unit">种</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-container">
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div id="weekly-chart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div id="category-chart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-container">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div id="hot-selling-chart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="chart-container">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>商品分类占比</span>
            </div>
          </template>
          <div id="category-chart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.dashboard-container {
  .dashboard-title {
    margin-bottom: 25px;
    font-size: 24px;
    color: #303133;
    font-family: 'Roboto';
    position: relative;

    &:after {
      content: '';
      position: absolute;
      top: 3px;
      left: -10px;
      width: 3px;
      height: 30px;
      background: linear-gradient(to top, rgb(0, 137, 34), #00b96b);
      border-radius: 3px;
      animation: move 2s linear infinite;
    }
    @keyframes move {
      0% {
        box-shadow: 0 0 0px 0 rgba(0, 137, 34, 0.5);
      }
      50% {
        box-shadow: 0 0 10px 0 rgba(0, 137, 34, 0.5);
      }
      100% {
        box-shadow: 0 0 0px 0 rgba(0, 137, 34, 0.5);
      }
    }
  }

  .data-cards {
    margin-bottom: 20px;

    .data-card {
      height: 140px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 15px !important;
      overflow: hidden;
      position: relative;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1) !important;
      }

      .card-icon {
        position: absolute;
        top: 15px;
        left: 15px;
        width: 40px;
        height: 40px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
      }

      .inventory-icon {
        background: linear-gradient(135deg, #00b96b, rgb(0, 137, 34));
      }

      .outbound-icon {
        background: linear-gradient(135deg, #409eff, #1677ff);
      }

      .inbound-icon {
        background: linear-gradient(135deg, #67c23a, #52c41a);
      }

      .products-icon {
        background: linear-gradient(135deg, #e6a23c, #faad14);
      }

      .stores-icon {
        background: linear-gradient(135deg, #909399, #8c8c8c);
      }

      .warning-icon {
        background: linear-gradient(135deg, #f56c6c, #ff4d4f);
      }

      .unit {
        font-size: 14px;
        margin-left: 5px;
        color: #909399;
      }

      &.warning-card {
        .el-statistic__content {
          color: #f56c6c;
        }
      }

      &:before {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: linear-gradient(to right, rgba(0, 137, 34, 0.7), rgba(0, 185, 107, 0.7));
        opacity: 0;
        transition: opacity 0.3s ease;
      }

      &:hover:before {
        opacity: 1;
      }

      :deep(.el-statistic__title) {
        font-size: 16px;
        margin-bottom: 10px;
        color: #606266;
      }

      :deep(.el-statistic__content) {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
      }
    }
  }

  .chart-container {
    margin-bottom: 20px;

    .chart-card {
      border-radius: 15px !important;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1) !important;
      }

      .chart {
        height: 350px;
        width: 100%;
      }
    }
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    .data-cards {
      .data-card {
        margin-bottom: 15px;
      }
    }

    .chart-container {
      .chart-card {
        margin-bottom: 15px;

        .chart {
          height: 300px;
        }
      }
    }
  }
}
</style>
